package com.example.demo.service.impl;

import com.example.demo.model.Category;
import com.example.demo.model.Drink;
import com.example.demo.repository.CategoryRepository;
import com.example.demo.repository.DrinkRepository;
import com.example.demo.service.ICategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CategoryJpaService implements ICategoryService {
    @Autowired
    public CategoryRepository categoryRepository;

    @Autowired
    public DrinkRepository drinkRepository;

    @Override
    public List<Category> getAllCategories() {
        return categoryRepository.findAll();
    }

    @Override
    public void addNewCategory(Category category) {
        categoryRepository.save(category);
    }

    @Override
    public Category getCategoryById(Integer id) {
        return categoryRepository.findById(id).orElse(null);
    }

    @Override
    public void updateCategory(Category category) {
         categoryRepository.save(category);
    }

    @Override
    @Transactional(rollbackFor = Exception.class) //数据库事务
    public void deleteCategory(Integer id) {
//        保持数据一致
//        1.将drink中关联该分类（category）的drink的分类（category）属性更新为null
//        1.1查询出和category关联的drink
        List<Drink> drinks = drinkRepository.findDrinksByCategory_Id(id);


//        1.2更新drinks
        for (Drink drink : drinks){
            drink.setCategory(null);
            drinkRepository.save(drink);
        }
//        2.删除指定分类
        categoryRepository.deleteById(id);
    }
}
